import kivy
from nmjeditor.data_access.controller import Controller, ControllerProxy
from nmjeditor.screens.detail_screen import DetailScreen
from nmjeditor.screens.main_screen import MainScreen


class ScreenFactory(object):
	screens = {
		"Main" : MainScreen,
	}
	def __init__(self, gui_queue, drawer):
		self.controller = Controller(gui_queue, drawer)
		self.proxy = ControllerProxy(self.controller.queue)
		self.controller.start()
		self._screens = {}
		self.build_all()
		self.current_screen = None
		self.root = None

	def get_controller(self):
		return self.proxy

	def stop(self):
		self.controller.stop()
		self.controller.join()

	def set_root(self, root):
		self.root = root

	def __getattr__(self, name):
		return getattr(self.current_screen, name)

	def build_all(self, ):
		self._screens["Main"] = MainScreen(self, self.proxy)

	def get_screen(self, name, command_queue, *args, **kwargs):
		if not self._screens.get(name, None):
			self._screens[name] = self.screens.get(name, DetailScreen)(command_queue, self.proxy, *args, **kwargs)
		return self._screens[name]

	def set_screen(self, screenname, *args, **kwargs):
		screen = self.get_screen(screenname, self, *args, **kwargs)
		if self.current_screen:
			self.root.remove_widget(self.current_screen)
		self.root.add_widget(screen)
		self.current_screen = screen


